package com.th.cash.th2.product

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lxj.xpopup.XPopup
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.toast
import com.th.resmodel.R
import com.th.resmodel.databinding.FragmentIdBinding
import com.th.cash.th2.product.UploadIdCardResponse.TqYJitBYappedNtyUfcF
import com.th.cash.th2.splash.PermissionDeniedPopup
import kotlinx.coroutines.launch
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File
import java.util.Locale

class IdFragment : VerifyBaseFragment<FragmentIdBinding>() {

    override var type = 4

    private var cameraLauncher: ActivityResultLauncher<Intent>? = null

    private var imgPath: String = ""

    var idData: TqYJitBYappedNtyUfcF? = null

    private val mViewModel by viewModels<ProductVm>()

    override fun startObserve() {
        lifecycleScope.launch {
            mViewModel.uiState.collect {
                when (it) {
                    is ProductState.Idle -> {

                    }

                    is ProductState.IdCardData -> {
                        if (it.data.MRZamUjLamppostNaUomFq.QylNBLMBombitaFwSlPhN.isNotEmpty()) {
                            mBinding.llUploadOcrStart.visibility = View.GONE
                            mBinding.llUploadOcrError.visibility = View.GONE
                            mBinding.llUploadOcrEnd.visibility = View.VISIBLE

                            mDataList.clear()
                            mDataList.addAll(it.data.MRZamUjLamppostNaUomFq.QylNBLMBombitaFwSlPhN)

                            idData = it.data.MRZamUjLamppostNaUomFq.TqYJitBYappedNtyUfcf

                            mBinding.rvUploadOcrList.adapter?.notifyDataSetChanged()
                        } else {
                            mBinding.llUploadOcrStart.visibility = View.VISIBLE
                            mBinding.llUploadOcrError.visibility = View.GONE
                            mBinding.llUploadOcrEnd.visibility = View.GONE
                        }
                    }

                    is ProductState.UploadIdCad -> {
                        mBinding.llUploadOcrStart.visibility = View.GONE
                        mBinding.llUploadOcrError.visibility = View.GONE
                        mBinding.llUploadOcrEnd.visibility = View.VISIBLE

                        idData = it.data.TqYJitBYappedNtyUfcf

                        mDataList.clear()
                        mDataList.addAll(it.data.QylNBLMBombitaFwSlPhN)
                        mBinding.rvUploadOcrList.adapter?.notifyDataSetChanged()
                    }

                    is ProductState.UploadIdCadError -> {
                        mBinding.llUploadOcrStart.visibility = View.GONE
                        mBinding.llUploadOcrError.visibility = View.VISIBLE
                        mBinding.llUploadOcrEnd.visibility = View.GONE
                    }

                    is ProductState.VerifySuccess -> {
                        nextPage(it.data.FqLBwdpDollarbirdSXQntyj.noneconomicSingle)
                    }

                    else -> {}
                }
            }
        }
    }

    override fun init() {
        mBinding.header.headTitle.text = "การรับรู้บัตรประจำตัว"

        initLauncher()
        initVerifyAdapter(mBinding.rvUploadOcrList)
        initClick()

        mViewModel.intentChannel.trySend(ProductIntent.InitIdCard(IdCardRequest(getPid())))
    }

    private fun initClick() {
        mBinding.header.headBack.setOnClickListener {
            back(4)
        }

        mBinding.ivSelectPhoto.setOnClickListener {
            showPicSelect()
        }

        mBinding.tvUploadOcrSubmit.setOnClickListener {
            if (mBinding.llUploadOcrEnd.visibility != View.VISIBLE) {
                showPicSelect()
                return@setOnClickListener
            }

            val params = mutableListOf<Pair<String, Any?>>()

            mDataList.forEach {
                if (it.DEaiqpxElectrodiagnosisXYIQybx == 0 && TextUtils.isEmpty(it.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc)) {
                    toast("กรุณากรอกรายการรับรองให้ครบถ้วน")
                    return@setOnClickListener
                }

                params.add(
                    Pair(
                        it.RAEdwRPQuaveringlyMOIghzQ.sQDRQmIUnexactingIeHvoQV,
                        it.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc
                    )
                )
            }

            idData?.let {
                params.add(
                    Pair(
                        it.sQDRQmIUnexactingIeHvoQV,
                        it.PxGEecSAntiwarMrDXISc
                    )
                )
            }

            mViewModel.intentChannel.trySend(
                ProductIntent.SaveIdCard(
                    IdCardSaveRequest(
                        getPid(),
                        params
                    )
                )
            )
        }
    }

    private fun showPicSelect() {
        XPopup.Builder(requireContext())
            .asCustom(
                PicSelectPopup(
                    requireContext()
                ).run {
                    clickListener = { position ->
                        if (position == 0) {
                            startAblum()
                        } else {
                            requestPermission()
                        }
                    }
                    this
                })
            .show()
    }

    private fun requestPermission() {
        XXPermissions.with(requireContext())
            // 申请单个权限
            .permission(
                Permission.CAMERA
            )
            // 申请多个权限
            //            .permission(Permission.Group.CALENDAR)
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            .unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        toast("ไม่ได้รับอนุญาตอย่างถูกต้อง")
                        return
                    }
                    startCamera()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        showPermissionDeniedPopup(permissions)
                    } else {
                        toast("ไม่ได้รับอนุญาตอย่างถูกต้อง")
                    }
                }
            })
    }

    private fun initLauncher() {
        cameraLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == RESULT_OK) {
                try {
                    mViewModel.loadStartLoading()

                    val builder: Luban.Builder? = if (!TextUtils.isEmpty(imgPath)) {
                        Luban.with(requireContext()).load(imgPath)
                    } else if (result.data?.data != null) {
                        Luban.with(requireContext()).load(result.data!!.data)
                    } else {
                        null
                    }

                    builder?.ignoreBy(100)?.filter { path ->
                        !(TextUtils.isEmpty(path) || path.lowercase(Locale.getDefault())
                            .endsWith(".gif"))
                    }?.setCompressListener(object : OnNewCompressListener {
                        override fun onStart() {
                        }

                        override fun onSuccess(source: String?, compressFile: File) {
                            mViewModel.intentChannel.trySend(ProductIntent.UploadIdCard(compressFile.absolutePath))
                        }

                        override fun onError(source: String, e: Throwable?) {
                            mViewModel.intentChannel.trySend(ProductIntent.UploadIdCard(source))
                        }
                    })?.launch()
                } catch (e: Exception) {
                    e.printStackTrace()
                    mViewModel.loadSuccess()
                }
            }
        }
    }

    private fun startAblum() {
        imgPath = ""
        val intent = Intent(Intent.ACTION_PICK, null)
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        cameraLauncher?.launch(intent)
    }

    private fun startCamera() {
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED || !Environment.isExternalStorageRemovable()) {
            val fileName =
                requireContext().getString(R.string.app_name) + "_camera_" + System.currentTimeMillis() + "_.jpg"
            val dir = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            val folder = File(dir, getString(R.string.app_name) + "camera")
            if (!folder.exists() && !folder.mkdir()) {

            }
            val tempFile = File(folder, fileName)
            imgPath = tempFile.path
            val imgUri: Uri = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                Uri.fromFile(tempFile)
            } else {
                FileProvider.getUriForFile(
                    requireContext(),
                    "${requireContext().packageName}.fileprovider",
                    tempFile
                )
            }

            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).run {
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                putExtra(MediaStore.EXTRA_OUTPUT, imgUri)
//                putExtra("android.intent.extras.CAMERA_FACING", 1)
                putExtra("autofocus", true)

                this
            }

            cameraLauncher?.launch(intent)
        }
    }

    private fun showPermissionDeniedPopup(permissions: MutableList<String>) {
        XPopup.Builder(requireContext())
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(PermissionDeniedPopup(requireContext()).run {

                clickListener = { agree ->
                    if (agree) {
                        XXPermissions.startPermissionActivity(requireContext(), permissions)
                    }
                }

                this
            })
            .show()
    }

    override fun onLazyInitData() {

    }

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    companion object {
        fun newInstance(): IdFragment {
            return IdFragment()
        }
    }

}